<template>
  <div class="main-home-page">
    <!-- 用户选项弹窗 -->
    <div v-if="showUserOptionsModal" class="user-options-modal-overlay" @click="closeUserOptionsModal">
      <div class="user-options-modal" @click.stop>
        <div class="user-option" @click="goToPersonalHome">
          <span class="option-icon">👤</span>
          <span class="option-text">个人主页</span>
        </div>
        <div class="user-option" @click="logout">
          <span class="option-icon">🚪</span>
          <span class="option-text">退出登录</span>
        </div>
      </div>
    </div>
    
    <!-- 顶部搜索和用户区域 -->
    <div class="top-bar">
      <div class="left-aligned-header-items">
        <div class="header-logo" @click="goToMainHome">
          <img src="../assets/logo.png" alt="Logo" class="logo">
          <span class="logo-text">小白盒</span>
        </div>
        <TopBarSearch />
      </div>
      <div class="user-profile">
        <img :src="currentUser.avatar" alt="用户头像" class="user-avatar" @click="toggleUserOptionsModal">
        <span class="username" @click="toggleUserOptionsModal" style="cursor: pointer;">{{ currentUser.nickname }}</span>
        <span class="message-icon" @click="goToMessageHome"></span>
      </div>
    </div>
    <el-dialog
      v-model="showLoginModal"
      width="320px"
      :show-close="false"
      center
      custom-class="login-required-modal"
    >
      <div style="text-align:center;font-size:20px;font-weight:bold;margin-bottom:20px;">该功能需要登录</div>
      <div style="display:flex;gap:16px;justify-content:center;">
        <el-button @click="showLoginModal = false" style="width:100px;">取消</el-button>
        <el-button type="primary" @click="goToLogin" style="width:100px;background:linear-gradient(90deg,#23272b,#43484d);border:none;">去登录</el-button>
      </div>
    </el-dialog>
    <div class="main-sections-wrapper">
      <div class="main-sections">
        <!-- 主内容区插槽 -->
        <div style="flex:1; min-width:0;">
          <slot name="main" />
          <activity-feed />
        </div>
        <!-- 热搜侧边栏 -->
        <div class="hot-community-sidebar">
          <div class="hot-title">热搜榜</div>
          <ul class="hot-list">
            <li v-for="(item, idx) in hotSearches" :key="idx" class="hot-item" @click="searchHotTopic(item)">
              <span :class="['hot-rank', `rank-${idx + 1}`]">{{ idx + 1 }}</span>
              <span class="hot-name">{{ item }}</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import TopBarSearch from '../components/TopBarSearch.vue';
import ActivityFeed from "@/activity/ActivityFeed.vue";
import { useRouter } from 'vue-router';
import { ref, onMounted } from 'vue';
import { currentUser } from '../user';
import axios from 'axios';

const router = useRouter();
const showLoginModal = ref(false);
const showUserOptionsModal = ref(false);
const hotSearches = ref([]);

// 获取热搜话题
const fetchHotTopics = async () => {
  try {
    const response = await axios.get('/search/history/hot');
    if (response.data.code === 200 && response.data.data) {
      // 从返回的话题对象中提取内容
      hotSearches.value = response.data.data.map(topic => topic.content);
    }
  } catch (error) {
    console.error('获取热搜话题失败:', error);
  }
};


// 点击热搜词进行搜索
const searchHotTopic = (keyword) => {
  // 使用事件总线发送事件，通知TopBarSearch组件填充搜索框
  window.dispatchEvent(new CustomEvent('fill-search-input', { 
    detail: { keyword }
  }));
  // 确保跳转到搜索页面
  setTimeout(() => {
    router.push({
      path: '/search',
      query: { q: keyword }
    });
  }, 100);
};

function goToMainHome() {
  router.replace('/mainpage').then(() => {
    // 页面跳转后刷新页面
    window.location.reload();
  });
}

function goToPersonalHome() {
  router.push(`/user/${currentUser.id}`);
}

// 切换用户选项弹窗
function toggleUserOptionsModal() {
  showUserOptionsModal.value = !showUserOptionsModal.value;
}

// 关闭用户选项弹窗
function closeUserOptionsModal() {
  showUserOptionsModal.value = false;
}

// 退出登录
function logout() {
  // 清空用户信息
  currentUser.id = null;
  currentUser.nickname = '默认用户';
  currentUser.avatar = '';
  
  // 清除本地存储
  localStorage.removeItem('user');
  
  // 跳转到登录页面
  router.push('/login').then(() => {
    // 页面跳转后刷新页面
    window.location.reload();
  });
  closeUserOptionsModal();
}

function goToMessageHome() {
  if (currentUser.id === 4) {
    showLoginModal.value = true;
  } else {
    router.push('/messagehome').then(() => {
      // 页面跳转后刷新页面
      window.location.reload();
    });
  }
}

function goToLogin() {
  showLoginModal.value = false;
  router.push('/login');
}

onMounted(() => {
  const user = JSON.parse(localStorage.getItem('user'));
  if (user) {
    currentUser.id = user.id;
    currentUser.nickname = user.nickname;
    currentUser.avatar = user.avatar;
  }
  
  // 获取热搜话题
  fetchHotTopics();
});
</script>

<style scoped>
.main-home-page {
  width: 100%;
  height: 100%;
  background-color: #f7f9fa;
  display: flex;
  flex-direction: column;
}

.top-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  height: 50px;
}

.left-aligned-header-items {
  display: flex;
  align-items: center;
  flex-grow: 1;
  width: 100%;
}

.header-logo {
  display: flex;
  align-items: center;
  height: 100%;
  margin-left: 24px;
  cursor: pointer;
}

.logo {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.logo-text {
  font-size: 20px;
  font-weight: bold;
  margin-right: 60px;
  width: 100px;
  color: #333;
}

.user-profile {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 100px;
}

.user-avatar {
  border-radius: 50%;
  margin-right: 10px;
  width: 30px;
  height: 30px;
  cursor: pointer;
  transition: box-shadow 0.2s;
}
.user-avatar:hover {
  box-shadow: 0 2px 8px rgba(52,152,219,0.15);
}

.username {
  font-weight: bold;
  margin-right: 20px;
  font-size: 15px;
  color: #000;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
}

/* 用户选项弹窗样式 */
.user-options-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  z-index: 1000;
}

.user-options-modal {
  position: absolute;
  top: 50px;
  right: 100px;
  width: 150px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.user-option {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-option:hover {
  background-color: #f5f5f5;
}

.option-icon {
  margin-right: 10px;
  font-size: 18px;
}

.option-text {
  font-size: 14px;
  color: #000000;
}

.message-icon {
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: inline-block;
  background-image: url('https://img.icons8.com/sf-regular/48/messaging-.png');
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  text-indent: -9999px;
  transition: filter 0.2s;
}
.message-icon:hover {
  filter: brightness(1.3);
}

.main-sections-wrapper {
  flex-grow: 1;
  margin-top: 50px;
  padding: 0;
  overflow-y: auto;
  height: calc(100vh - 50px);
  width: 100%;
  display: flex;
  justify-content: center;
}
.main-sections {
  display: flex;
  flex-grow: 1;
  gap: 0;
  height: 100%;
  max-width: 1200px;
  width: 100%;
  padding: 0;
}
.hot-community-sidebar {
  flex-basis: 260px;
  flex-shrink: 0;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  margin-left: 0;
  padding: 20px 0 10px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 400px;
  height: fit-content;
  margin-top: 50px;
}
.hot-title {
  font-size: 18px;
  font-weight: bold;
  color: #222;
  margin-bottom: 18px;
  display: flex;
  align-items: center;
  gap: 8px;
}
.hot-title::before {
  content: '\1F525';
  font-size: 20px;
  margin-right: 4px;
}
.hot-list {
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
}
.hot-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background 0.18s;
  cursor: pointer;
}
.hot-item:last-child {
  border-bottom: none;
}
.hot-item:hover {
  background: #f0f6ff;
}
.hot-icon {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}
.hot-name {
  flex: 1;
  font-size: 15px;
  color: #333;
  margin-left: 8px;
}
.hot-rank {
  width: 22px;
  display: inline-block;
  text-align: center;
  font-weight: bold;
  margin-right: 8px;
}
.rank-1 { color: #ff4d4f; }
.rank-2 { color: #ff7a45; }
.rank-3 { color: #ffa940; }
.hot-more {
  text-align: right;
  color: #888;
  font-size: 13px;
  margin: 12px 20px 0 0;
  cursor: pointer;
}
/* 滚动条美化 */
::-webkit-scrollbar {
  width: 8px;
  background: #f0f2f5;
}
::-webkit-scrollbar-thumb {
  background: #e0e0e0;
  border-radius: 4px;
}
/* 移动端适配 */
@media (max-width: 768px) {
  .main-sections {
    flex-direction: column;
    padding: 0 8px;
    max-width: 100%;
  }
  .hot-community-sidebar {
    margin-left: 0;
    margin-top: 24px;
    width: 100%;
  }
  .top-bar {
    padding: 0 8px;
  }
}
@media (max-width: 900px) {
  .hot-community-sidebar {
    margin-left: 0;
    margin-top: 24px;
    width: 100%;
    min-width: 160px;
    padding: 16px 8px 10px 8px;
    position: static;
    top: auto;
  }
}
.login-required-modal .el-dialog__header,
.login-required-modal .el-dialog__footer {
  display: none;
}
.login-required-modal .el-dialog__body {
  background: rgba(0,0,0,0.7);
  color: #fff;
  border-radius: 12px;
  padding: 32px 16px 24px 16px;
}
</style>